<template>
    <div>
        <div class="top-panel">
            <el-card style="height: 150px;">
                <div class="avatar">
                    <el-avatar :size="99" :src="circleUrl" />
                    <div class="upload" @click="dialogVisible = true">
                        <el-icon color="#409eff" :size="14">
                            <Camera />
                        </el-icon>
                    </div>
                </div>
                <div class="grid-container">
                    <div class="grid-item">
                        <span class="grid-name">店铺:</span><span class="grid-con">{{ userInfo?.storeName }}</span>
                    </div>
                    <div class="grid-item">
                        <span class="grid-name">账号:</span><span class="grid-con">{{ userInfo?.nickName }}</span>
                    </div>
                    <div class="grid-item">
                        <span class="grid-name">姓名:</span><span class="grid-con">{{ userInfo?.contactName }}</span>
                    </div>
                    <div class="grid-item">
                        <span class="grid-name">余额:</span><span class="grid-con">{{ userInfo?.balance == null ? '0.00' :
                            userInfo.balance }}</span>
                    </div>
                    <div class="grid-item">
                        <span class="grid-name">手机:</span><span class="grid-con">{{ userInfo?.phone }}</span>
                    </div>
                    <div class="grid-item">
                        <span class="grid-name">邮箱:</span><span class="grid-con">{{ userInfo?.email }}</span>
                    </div>
                    <div class="grid-item">
                        <span class="grid-name">状态:</span><span class="grid-con">{{ userInfo?.businessStatusName
                        }}</span>
                    </div>
                    <div class="grid-item">
                        <span class="grid-name">营业:</span><span class="grid-con">{{ userInfo?.openTime }}</span>
                    </div>
                    <div class="grid-item">
                        <span class="grid-name">注册:</span><span class="grid-con">{{ userInfo?.createAtStr }}</span>
                    </div>
                    <div class="grid-item">
                        <span class="grid-name">地址:</span><span class="grid-con">{{ userInfo?.address }}</span>
                    </div>
                    <div class="grid-item">
                        <span class="grid-name">描述:</span><span class="grid-con">{{ userInfo?.description }}</span>
                    </div>
                </div>
            </el-card>
        </div>
        <el-card class="form-card" shadow="hover">
            <h3 class="form-title">基础信息</h3>

            <!-- 关键修复：给 el-form 加 label-width 统一标签宽度 -->
            <el-form ref="formRef" :model="userInfo" :rules="rules" class="user-form" label-width="80px">
                <!-- 两列布局容器 -->
                <div class="form-grid">
                    <!-- 店铺 -->
                    <el-form-item label="店铺" prop="storeName" class="form-item">
                        <el-input v-model="userInfo.storeName" placeholder="请输入店铺名称" />
                    </el-form-item>

                    <!-- 姓名 -->
                    <el-form-item label="姓名" prop="contactName" class="form-item">
                        <el-input v-model="userInfo.contactName" placeholder="请输入姓名" />
                    </el-form-item>

                    <el-form-item label="开业" prop="openingTime" class="form-item">
                        <el-time-picker v-model="userInfo.openingTime" placeholder="选择开业时间" format="HH:mm"
                            value-format="HH:mm" :picker-options="{ selectableRange: '00:00-23:59' }"
                            style="width: 100%;" />
                    </el-form-item>
                    <el-form-item label="歇业" prop="closingTime" class="form-item">
                        <el-time-picker v-model="userInfo.closingTime" placeholder="选择歇业时间" format="HH:mm"
                            value-format="HH:mm" :picker-options="{ selectableRange: '00:00-23:59' }"
                            style="width: 100%;" />
                    </el-form-item>

                    <el-form-item label="地址" prop="address" class="form-item">
                        <el-input v-model="userInfo.address" placeholder="请输入地址" />
                    </el-form-item>

                    <!-- 描述 -->
                    <el-form-item label="描述" prop="description" class="form-item full-width">
                        <el-input v-model="userInfo.description" type="textarea" placeholder="请输入描述信息" rows="4" />
                    </el-form-item>
                </div>

                <!-- 按钮组 -->
                <div class="form-actions">
                    <el-button type="primary" @click="handleSubmit" class="animated-btn">保存</el-button>
                    <el-button @click="handleReset" class="animated-btn">重置</el-button>
                </div>
            </el-form>
        </el-card>
        <!-- 头像裁剪弹窗 -->
        <AvatarCropper title="上传头像" v-model:show="dialogVisible" @crop="handleCrop" />
    </div>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted } from 'vue';
import { Camera } from '@element-plus/icons-vue';
import axios from 'axios'
import AvatarCropper from '@/components/AvatarCropper.vue';

const { proxy } = getCurrentInstance();
const circleUrl = ref('');
let userInfo = ref({});

const dialogVisible = ref(false)

const api = {
    // 获取头像
    getAvatar: '/file/getAvatar',
    // 上传头像
    uploadAvatar: '/api/merchant/uploadAvatar',
    // 获取用户信息
    getUserInfo: '/merchant/getUserInfo',
    // 修改商家信息
    updateMerchantInfo: '/merchant/updateMerchantInfo',
};

// 表单数据
const form = ref({
    phone: '',
    email: '',
    address: '',
    description: '',
})

// 表单验证规则
const rules = {
    storeName: [
        { required: true, message: '请输入店铺名称', trigger: 'blur' }
    ],
    contactName: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
    ],
    openingTime: [
        { required: true, message: '开业时间不能为空', trigger: 'blur' }
    ],
    closingTime: [
        { required: true, message: '歇业时间不能为空', trigger: 'blur' }
    ]
}

// 提交表单
const handleSubmit = () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            let params = {}
            Object.assign(params, userInfo.value)
            let result = await proxy.Request({
                url: api.updateMerchantInfo,
                params,
            });

            if (!result) {
                return;
            }
            if (result.code === 200) {
                proxy.$message.success("保存成功");
                getUserInfo()
            }
        } else {
            ElMessage.error('表单校验失败，请检查！')
            return false
        }
    })
}

// 重置表单
const handleReset = () => {
    formRef.value.resetFields()
}

// 表单引用（用于调用校验、重置方法）
const formRef = ref()

// 获取头像
const getAvatar = async () => {
    try {
        const res = await proxy.Request({
            url: api.getAvatar,
            responseType: 'blob'
        });
        if (res) {
            const avatarUrl = URL.createObjectURL(res);
            circleUrl.value = avatarUrl;
        }
    } catch (err) {
        console.error('获取头像失败', err);
    }
};

// 获取裁剪后的图片
const handleCrop = async (croppedImageUrl) => {
    // 1. 获取裁剪后的 Blob
    const blob = await fetch(croppedImageUrl).then(res => res.blob());

    // 2. 用 canvas 转 JPG，去掉透明背景
    const img = await createImageBitmap(croppedImageUrl);
    const canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    const ctx = canvas.getContext('2d');
    ctx.fillStyle = '#ffffff'; // 白色背景
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(img, 0, 0);

    const jpgBlob = await new Promise(resolve =>
        canvas.toBlob(resolve, 'image/jpeg', 1)
    );

    // 3. 上传到后端
    const formData = new FormData();
    formData.append('file', jpgBlob, 'avatar.jpg'); // 加文件名
    const result = await axios.post(api.uploadAvatar, formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
    });

    if (result.data.code === 200) {
        proxy.$message.success("上传成功");
        getAvatar();
    }
};

const getUserInfo = async () => {
    let result = await proxy.Request({
        url: api.getUserInfo,
    });

    if (result.code === 200) {
        userInfo.value = result.data
    }
}

onMounted(() => {
    getAvatar();
    getUserInfo();
});
</script>

<style lang="scss" scoped>
.top-panel {
    .avatar {
        width: 100px;
        height: 100px;
        position: relative;
        display: inline-block;
        margin-top: 10px;

        .upload {
            position: absolute;
            bottom: 0;
            right: 0;
            cursor: pointer;
            background-color: #b6d9ee;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            line-height: 26px;
            text-align: center;
            transition: all 0.3s ease;

            &:hover {
                background-color: #409eff;

                :deep(svg) {
                    color: white !important;
                }
            }
        }
    }

    .grid-container {
        display: flex;
        flex-wrap: wrap;
        gap: 16px;
        margin-left: 230px;
        margin-top: -110px;

        .grid-item {
            flex: 0 0 calc(20%);
            height: 30px;
            display: flex;
            justify-content: flex-start;
            align-items: center;
            width: 200px;
            border-radius: 6px;
            padding-left: 10px;
            cursor: default;

            .grid-name {
                width: 32px;
                font-size: 14px;
                color: rgb(72, 70, 70);
                margin-right: 10px;
            }

            .grid-con {
                width: 200px;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
        }
    }
}

.form-card {
    padding: 25px;
    border-radius: 12px;
    margin-top: 30px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
}

.form-card:hover {
    box-shadow: 0 12px 32px rgba(0, 0, 0, 0.12);
}

.form-title {
    background: linear-gradient(90deg, #2e9bc9, #3592d8);
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
    text-align: center;
    margin-bottom: 30px;
    font-size: 24px;
    font-weight: 600;
    animation: titleGradient 3s ease infinite;
    background-size: 200% auto;
}

@keyframes titleGradient {
    0% {
        background-position: 0% 50%;
    }

    50% {
        background-position: 100% 50%;
    }

    100% {
        background-position: 0% 50%;
    }
}

.form-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    align-items: center;
}

.form-item {
    margin-bottom: 0;
    display: flex;
    align-items: center;
}

.full-width {
    grid-column: span 2;
}

.form-actions {
    display: flex;
    justify-content: center;
    gap: 15px;
    margin-top: 30px;
}

.animated-btn {
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    padding: 8px 24px;
}

.animated-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.el-input__wrapper),
:deep(.el-time-picker__wrapper),
:deep(.el-textarea__wrapper) {
    transition: all 0.3s ease;
    border-radius: 6px;
}

:deep(.el-input__wrapper:focus-within),
:deep(.el-time-picker__wrapper:focus-within),
:deep(.el-textarea__wrapper:focus-within) {
    box-shadow: 0 0 0 2px rgba(66, 185, 131, 0.2);
    border-color: #42b983;
}

@media (max-width: 768px) {
    .form-grid {
        grid-template-columns: 1fr;
    }

    .full-width {
        grid-column: span 1;
    }

    .top-panel .grid-container {
        margin-left: 0;
        margin-top: 20px;
        justify-content: center;
    }
}

:deep(.el-dialog__body) {
    padding: 20px;
}

:deep(.el-time-picker__input) {
    height: 32px;
    line-height: 32px;
}
</style>